package cms.controllers {
  import org.restfulx.Rx;
  import org.restfulx.collections.RxCollection;
  import org.restfulx.events.CacheUpdateEvent;
  import org.restfulx.utils.RxUtils;
  
  import cms.models.Deposit;
  import cms.models.Household;
  import cms.models.Payment;
  import cms.models.Person;
  
  [Bindable]
  public class ModelsController {
    
    public static var controller:ModelsController;
            
    private var _selectedDeposit:Deposit;
    
    public var deposits:RxCollection;
    
    public var households:RxCollection;
    
    public var payments:RxCollection;
        
    public var people:RxCollection;
    
    public function ModelsController(enforcer:SingletonEnforcer) {
      Rx.models.addEventListener(CacheUpdateEvent.ID, onCacheUpdate);
      Rx.models.indexAll(Deposit, Household, Payment, Person);
    }

    private function onCacheUpdate(event:CacheUpdateEvent):void {
      if (event.isFor(Deposit)) {
        deposits = Rx.models.cached(Deposit);
      } else if (event.isFor(Household)) {
        households = Rx.models.cached(Household);
      } else if (event.isFor(Payment)) {
        payments = Rx.models.cached(Payment);
      } else if (event.isFor(Person)) {
	  people = Rx.models.cached(Person);
      } else {
        var prop:String = RxUtils.toCamelCase(Rx.models.state.controllers[event.fqn]);
        if (hasOwnProperty(prop)) {
          this[prop] = Rx.models.cache.data[event.fqn];
        }
      }
    }
    
    public function get selectedDeposit():Deposit {
      return _selectedDeposit;
    }
    
    public function set selectedDeposit(deposit:Deposit):void {
      _selectedDeposit = (Deposit.ANY == deposit) ? null : deposit;
      filterPayments();
    }

    public function filterPayments():void {
	payments.filterFunction = function(payment:Payment):Boolean {
	    return payment.deposit == selectedDeposit;
	};
	payments.refresh();
    }
    
    public function paymentOfSelectedDeposit(payment:Payment):Boolean {
      return (selectedDeposit) ? payment.deposit == selectedDeposit : true;
    }
    
    public static function get instance():ModelsController {
      initialize();
      return controller;
    }
    
    public static function initialize():void {
      if (!controller) controller = new ModelsController(new SingletonEnforcer);
    }
  }
}

class SingletonEnforcer {}